package com.sea.base.widget

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.WindowManager
import androidx.core.widget.NestedScrollView
import com.sea.base.activities.R
import com.sea.base.ext.global.screenWidthRatio

/**
 * 支持开关手指滑动事件
 */
class MyNestedScrollView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : NestedScrollView(context, attrs, defStyleAttr) {
    var isScrollable = true

    /**
     * 压缩模式：压缩后EditText弹起后底部至少要留的距离，如果想展示到底部可以写一个很大值
     * 一般配合[FitsSystemWindowsFrameLayout]、[BaseFullscreenKtActivity]、[WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE]使用
     * 实现逻辑为取巧方式，取巧原理见super.[onSizeChanged]的方法的逻辑
     */
    var adjustResizeEditTextMinBottomMargin = 0

    init {
        if (attrs != null) {
            val ta: TypedArray = context.obtainStyledAttributes(attrs,
                R.styleable.MyNestedScrollView
            )
            isScrollable = ta.getBoolean(R.styleable.MyNestedScrollView_isScrollable, isScrollable)
            adjustResizeEditTextMinBottomMargin = ta.getDimensionPixelOffset(R.styleable.MyNestedScrollView_adjustResizeEditTextMinBottomMargin, adjustResizeEditTextMinBottomMargin)
            ta.recycle()
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(ev: MotionEvent) = if (isScrollable) super.onTouchEvent(ev) else false

    private var isAdjustResizing = false
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        isAdjustResizing = oldh - h > 0.4.screenWidthRatio
        super.onSizeChanged(w, h, oldw, oldh)
        isAdjustResizing = false
    }

    override fun computeScrollDeltaToGetChildRectOnScreen(rect: Rect): Int {
        if (isAdjustResizing) {
            isAdjustResizing = false
            rect.set(rect.left, rect.top, rect.right, rect.bottom + adjustResizeEditTextMinBottomMargin)
        }
        return super.computeScrollDeltaToGetChildRectOnScreen(rect)
    }
}